package com.chukun.netty.tcpdecoder;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

public class TcpClientHandler extends SimpleChannelInboundHandler<PersonProtocal> {
    private int counter;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String content="TcpClientHandler channelActive";
        for(int i=0;i<10;i++){
            PersonProtocal personProtocal = new PersonProtocal();
            byte[] bufferContent = content.getBytes(Charset.forName("utf-8"));
            int length = content.getBytes(Charset.forName("utf-8")).length;
            personProtocal.setLength(length);
            personProtocal.setContent(bufferContent);
            ctx.writeAndFlush(personProtocal);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PersonProtocal msg) throws Exception {
        System.out.println("received from server : "+new String(msg.getContent(),Charset.forName("utf-8"))+" count :"+(++counter));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
